# coding=utf-8
import os
import time
import requests
import pytest
from py.xml import html
from selenium import webdriver
from selenium.webdriver import Remote
from .config import RunConfig
from loguru import logger

logger.remove(handler_id=None)
logger.add(r"E:\CloudPlatform\case_logs\test111123.log", encoding="utf-8", retention="7 days", backtrace=True, enqueue=True)

report_path = r"E:\CloudPlatform\case_reports"

def pytest_html_report_title(report):
        report.title = "UI自动化测试报告"

def pytest_html_results_table_header(cells):
    cells.insert(2, html.th('用例描述'))
    
    cells.pop()
    
def pytest_html_results_table_row(report, cells):
    cells.insert(2, html.td(report.description))
    
    cells.pop()
    
def pytest_configure(config):
    config._metadata.pop("JAVA_HOME")
    config._metadata.pop("Plugins")
    config._metadata['开始时间'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    config._metadata['测试人'] = '张泽旺'
    
    
def pytest_runtest_call(item):
    logger.info('开始执行用例-%s' % item.function.__name__.split("test_")[-1])
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    report.description = description_html(item.function.__doc__)
    extra = getattr(report, 'extra', [])
    if report.when == 'call' or report.when == 'setup':
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):

            img_base64 = capture_screenshots()
            html = """<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:304px;height:228px;"
                            onclick="const img = new Image()
                                    img.src = 'data:image/png;base64,%s'
                                    const newWin = window.open('', '_blank')
                                    newWin.document.write(img.outerHTML)
                                    newWin.document.close()"
                            align="right"/></div>""" % (img_base64, img_base64)
            extra.append(pytest_html.extras.html(html))
        report.extra = extra

def description_html(desc):
    if desc is None:
        return "No case description"
    desc_ = ""
    for i in range(len(desc)):
        if i == 0:
            pass
        elif desc[i] == '\n':
            desc_ = desc_ + ";"
        else:
            desc_ = desc_ + desc[i]

    desc_lines = desc_.split(";")
    desc_html = html.html(
        html.head(
            html.meta(name="Content-Type", value="text/html; charset=latin1")),
        html.body(
            [html.p(line) for line in desc_lines]))
    return desc_html
def capture_screenshots():
    global driver
    base64_img = driver.get_screenshot_as_base64()
    return base64_img

@pytest.fixture(scope='session', autouse=True)
def driver():
    global driver
    options = webdriver.ChromeOptions()

    driver = Remote(command_executor='http://127.0.0.1:4444/wd/hub',
                    options=options)
    driver.maximize_window()
    driver.implicitly_wait(10)
    RunConfig.driver=driver
    driver.get("https://baidu.com")
    return driver
@pytest.fixture(scope="session", autouse=True)
def close():
    yield driver
    driver.quit()
    logger.info("test end!")